package cn.com.main;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.ECGenParameterSpec;
import java.util.Base64;

/**
 * 密钥对生成器
 *
 * @author LiuGuodong
 * @date 2024/03/20
 */
public class MyKeyPairGenerator {

    public static byte[] generateSM4Key() {
        SecureRandom secureRandom = new SecureRandom();
        byte[] key = new byte[16];
        secureRandom.nextBytes(key);
        return key;
    }

    @Test
    public void sM4Key() {
        try {
            byte[] sm4Key = generateSM4Key();
            System.out.println("Generated SM4 Key: " + Base64.getEncoder().encodeToString(sm4Key));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void keyPairGenerator() throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        // 生成密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
        ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("sm2p256v1");
        keyPairGenerator.initialize(ecGenParameterSpec);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 获取公钥和私钥
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        System.out.println("公钥：" + Base64.getEncoder().encodeToString(publicKey.getEncoded()));
        System.out.println("私钥：" + Base64.getEncoder().encodeToString(privateKey.getEncoded()));
    }

    @Test
    public void main1() throws Exception {
        // 注册 Bouncy Castle 提供程序
        Security.addProvider(new BouncyCastleProvider());

        // 创建密钥对生成器
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");

        // 初始化密钥对生成器，指定算法和密钥长度
        keyPairGenerator.initialize(256);

        // 生成密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        System.out.println("公钥：" + Base64.getEncoder().encodeToString(publicKey.getEncoded()));
        System.out.println("私钥：" + Base64.getEncoder().encodeToString(privateKey.getEncoded()));

        // 将公钥和私钥保存到文件中
        saveToFile("src/main/resources/publicKey.pem", keyPair.getPublic().getEncoded());
        saveToFile("src/main/resources/privateKey.pem", keyPair.getPrivate().getEncoded());
    }

    private static void saveToFile(String fileName, byte[] content) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(fileName)) {
            fos.write(content);
        }
        System.out.println(fileName + " 文件已保存成功！");
    }
}
